package com.city.ossservice.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.city.ossservice.service.OssService;
import com.city.ossservice.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: Cheng
 * Date: 2020/6/14
 * Time: 23:11
 * Description: No Description
 */
@Service//注入的是impl类，接受的类型为接口，接口为代理
public class OssServiceImpl implements OssService {
    @Override
    public String uploadOssFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
        String avatarFile;
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream =file.getInputStream();
            avatarFile=file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            avatarFile=uuid+avatarFile;

            //按日期分类 2020/6/15/01.jpg
            //获取当前日期
            String time = new DateTime().toString("yyyy/MM/dd");
            avatarFile=time+"/"+avatarFile;

            ossClient.putObject(bucketName,avatarFile, inputStream);
            ossClient.shutdown();
            //返回上传到阿里云oss的地址
            //https://hello-edu.oss-cn-beijing.aliyuncs.com/a.jpg
            String url="https://"+bucketName+"."+endpoint+"/"+avatarFile;
            return url;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }
}
